﻿using Entity;
using Logics;

namespace Services.Common;

/// <summary>
/// 提现接口
/// </summary>
[Authorize, ApiDescriptionSettings("提现")]
public class CashServices : BaseServices
{
    private readonly ISqlSugarClient db;

    private readonly MoneyLogics money;

    /// <summary>
    /// 提现接口
    /// </summary>
    /// <param name="db"></param>
    /// <param name="money"></param>
    public CashServices(ISqlSugarClient db, MoneyLogics money)
    {
        this.db = db;
        this.money = money;
    }

    /// <summary>
    /// 通用提现
    /// </summary>
    /// <param name="price"></param>
    /// <param name="accountId"></param>
    /// <returns></returns>
    public async Task<object> Cash(decimal price, int accountId)
    {
        if (price < 10) return No("提现金额最低10元");

        var account = await db.Queryable<Entity.CashAccount>()

            .FirstAsync(x => x.UserId == AUTOID && x.Role == ROLE);

        if (account == null) return No("错误的提现账户，请检查账户是否存在！");

        //提现手续费
        decimal servicePrice = price > 100 ? price * 0.03M : 3;

        //提现金额 = 提现金额 - 手续费
        decimal cashPrice = price - servicePrice;

        var cashLog = new Entity.Cash
        {
            Price = cashPrice,

            RealPrice = price,

            ServicePrice = servicePrice,

            CashAccountId = account.Id,

            CashName = account.Name,

            CashPhone = account.Phone,

            Role = ROLE,

            UserId = AUTOID,

            State = Entity.CashStatus.审核中,
        };

        try
        {
            db.Ado.BeginTran();

            bool state = false;

            int logId = 0;

            var model = new Dto.ChangeMoneyAndLog
            {
                Price = price,

                moneyType = MoneyType.提现,

                Type = 0,

                OrderId = 0,

                Uid = AUTOID,
            };

            if (ROLE == Enums.TokenRole.客户) (state, logId) = await money.Client(model);

            if (ROLE == Enums.TokenRole.商家) (state, logId) = await money.Store(model);

            if (ROLE == Enums.TokenRole.代理) (state, logId) = await money.Proxy(model);


            if (!state) throw new Exception("");

            cashLog.MoneyLogId = logId;

            state = await db.Insertable(cashLog).ExecuteCommandAsync() > 0;

            if (!state) throw new Exception("");

            db.Ado.CommitTran();

            return Ok("申请成功");

        }
        catch (Exception)
        {
            db.Ado.RollbackTran();

            return No("提现失败");
        }


    }

    /// <summary>
    /// 获取账户
    /// </summary>
    /// <returns></returns>
    public async Task<object> GetAccount()
    {
        var data = await db.Queryable<Entity.CashAccount>()

            .Where(x => x.Role == ROLE && x.UserId == AUTOID)

            .ToListAsync();

        return Ok(data);
    }

    /// <summary>
    /// 编辑账户
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public async Task<object> EditAccount(Entity.CashAccount data)
    {
        data.UserId = AUTOID;

        data.Role = ROLE;

        bool state = await db.Storageable(data).ExecuteCommandAsync() > 0;

        return Msg(state);
    }

    /// <summary>
    /// 提现记录
    /// </summary>
    /// <param name="state"></param>
    /// <returns></returns>
    public async Task<object> GetLog(CashStatus state)
    {
        var data = await db.Queryable<Entity.Cash>()

            .WhereIF(ROLE == ROLE, x => x.UserId == AUTOID)

            .Where(x => x.State == state)

            .OrderBy(x => x.Id, OrderByType.Desc)

            .ToPagedListAsync(PageNo, PageSize);

        return Ok(data);
    }
}
